$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL +'news/manage/list',
        datatype: "json",
        colModel: [
            { label: '资讯id', name: 'id', index: "id", width: 45, key: true,hidden:true },
            { label: '分类', name: 'classifiedsName',width: 45},
            { label: '类型', name: 'typeName', width: 45},
            { label: '标题', name: 'newsTitle'},
            { label: '创建时间', name: 'createTime',width: 70},
            { label: '状态', name: 'status', width: 40, formatter: function(value, options, row){
                    return value === "0" ?
                        '<span class="label label-danger">未发布</span>' :
                        '<span class="label label-success">已发布</span>';
            }}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.result",
            page: "page.pageNo",
            total: "page.totalPages",
            records: "page.total"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});

var vm = new Vue({
    el:'#classifieds',
    data:{
        q:{
            newsTitle: null
        },
        editor:false,
        showList: true,
        showVideo:false,
        videoUpload:false,
        coverImg:true,
        showCoverImg:false,
        checked:false,
        title:null,
        list:[],
        news:{
            id:null,
            newsTitle:null,
            newsContent:null,
            classifiedId:null,
            classifiedsName:null,
            typeCode:null,
            videoUrl:null,
            profile:null,
            newsCover:null,
            status:null
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        detail:function(){
            vm.getNewsClassified();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增资讯分类";
            vm.editor = true;
            editor.txt.html('');
            vm.showCoverImg=false;
            vm.showVideo = false;
            vm.news.newsTitle = null;
            vm.news.typeCode = "article";
            vm.news.classifiedId=null;
            vm.checked = true;
            vm.getNewsClassified();
        },
        update: function () {
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            $.get(baseURL + "news/manage/info/"+id, function(r){
                if (r.code === "success"){
                    if (r.data.status === "1"){
                        alert("已经发布的资讯不能修改")
                    } else {
                        vm.showList = false;
                        vm.editor = true;
                        vm.showCoverImg = true;
                        vm.showVideo = true;
                        vm.title = "修改资讯分类";
                        vm.news = r.data;
                        editor.txt.html(r.data.newsContent);
                        vm.getNewsClassified();
                    }
                } else {
                    alert(r.message)
                }
            });
            /*$.get(baseURL + "news/manage/info/"+id, function(r){
                vm.news = r.data;
                editor.txt.html(r.data.newsContent)
            });*/
        },
        del: function () {
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "news/manage/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function(r){
                        if(r.code === 'success'){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function () {
            var url = vm.news.id == null ? "news/manage/save" : "news/manage/update";
            if (vm.validateData(vm.news.typeCode)) {
                vm.news.newsContent = editor.txt.html();
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.news),
                    success: function(r){
                        if(r.code === 'success'){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.message);
                        }
                    }
                });
            } else {
                return
            }
        },
        reload: function () {
            vm.showList = true;
            vm.editor = false;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'newsTitle': vm.q.newsTitle},
                page:page
            }).trigger("reloadGrid");
        },
        publish:function(){
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "news/manage/publish",
                contentType: "application/json",
                data: JSON.stringify({id:id}),
                success: function(r){
                    if(r.code === 'success'){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.message);
                    }
                }
            });
        },
        getNewsClassified:function () {
            $.get(baseURL + "news/classifieds/findAll", function(r){
                vm.list = r.list;
            });
        },
        // 动态渲染
        isShow:function (flag) {
            if (flag){
                vm.videoUpload = true;
                vm.vodeoProfile = true;
                vm.editor = false;
                vm.checked = false;
            } else {
                vm.editor = true;
                vm.videoUpload = false;
                vm.vodeoProfile = false;
            }
        },
        validateData:function (typeCode) {
            if (vm.news.classifiedId == null || vm.news.classifiedId.trim() == ""){
                vm.tips("请选择资讯类型！",'classifiedId');
                return false;
            }
            if (vm.news.newsTitle == null || vm.news.newsTitle.trim() == ""){
                vm.tips("标题不能为空！",'title');
                return false;
            }
            if (vm.news.newsCover == null || vm.news.newsCover.trim() == ""){
                vm.tips("请上传封面图片！",'uploadCover');
                return false;
            }
            if (vm.news.profile == null || vm.news.profile.trim() == ""){
                vm.tips("简介不能为空！",'profile');
                return false
            }
            // 文章类型校验
            if ("article" == typeCode){
                if (editor.txt.text() == null || editor.txt.text().trim() == ""){
                    vm.tips("编辑区域不能为空！",editor.imgMenuId);
                    return false
                }
            } else {
                //视频类型校验
                if (vm.news.videoUrl == null || vm.news.videoUrl.trim() == ""){
                    vm.tips("请上传视频！",'uploadVideo');
                    return false
                }
            }
            return true;
        },
        tips:function (msg,tag) {
            layer.tips(msg, '#'+tag,{tips: [2, '#CC4FC8']});
        }
    }
});
/*富文本编辑*/
var E = window.wangEditor;
var editor = new E('#editor1');
editor.customConfig.uploadImgServer = '/upload/image';
editor.customConfig.uploadFileName = 'files';
editor.customConfig.uploadImgHooks = {
    // 处理服务端返回的字符串
    customInsert: function (insertImg, result, editor) {
        if (result.code === 'success'){
            var url = result.data.fileUrl;
            insertImg(url)
        } else {
            layer.alert(result.message)
        }
    }
};
// 监听编辑区域，替换图片URL
editor.customConfig.onchange = function (html) {
    var imgs = document.getElementById(editor.textElemId).getElementsByTagName('img');
    if (imgs.length>0){
        for(i=0;i<imgs.length;i++){
            var imgUrl = imgs[i].src;
            if (!urlRegEx(imgUrl)){
                $.ajax({
                    type: "GET",
                    url: baseURL + "upload/uploadByUrl/image",
                    contentType: "application/json",
                    async : false,
                    data: {url:imgUrl},
                    success: function(r){
                        if(r.code === 'success'){
                            imgs[i].src = r.data.fileUrl;
                        }
                    }
                });
            }
        }
    }
};
editor.create();
// 截取图片URL校验是否为自己文件服务器地址
function urlRegEx(url) {
    //var url = "http://img.qiniu.vp359.com/0092746c8ecf45589b7127f9526700f9.png";
    //var re = /(\w+):\/\/([^\:|\/]+)(\:\d*)?(.*\/)([^#|\?|\n]+)?(#.*)?(\?.*)?/i;
    var reg = /http[s]?:\/\/(.*?)([:\/]|$)/;
    var arr = url.match(reg);
    console.info(arr[1]);
    if (arr[1]=="img.qiniu.vp359.com"){
        return true;
    }
    return false;
};

layui.use('upload', function() {
    var $ = layui.jquery,
        upload = layui.upload;
    //图片上传
    var uploadInst = upload.render({
        elem: '#uploadCover',
        url: baseURL +'upload/image',
        field:'files',
        before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                vm.showCoverImg=true;
                $('#showImg').attr('src', result);
            });
            var index = layer.load(1,{ shade: [0.5,'#A4A4A4']});
        },
        done: function(res){
            if(res.code === 'success'){
                vm.news.newsCover = res.data.fileUrl;
                layer.close(layer.index);
            }
        }
    });
    // 视频上传
    upload.render({
        elem: '#uploadVideo',
        url: '/upload/video',
        field:'files',
        accept: 'video',
        size:20*1024,
        before:function(obj){
            /*加载层*/
            var index = layer.load(1, { shade: [0.5,'#A4A4A4'] });
        },
        done: function(res){
            if(res.code === 'success'){
                vm.news.videoUrl = res.data.fileUrl;
                vm.showVideo = true;

                layer.close(layer.index);
            }
        }
    });
});